package com.zjnu.oss.servlet;


import com.zjnu.oss.model.Student;
import com.zjnu.oss.util.MyBatisUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zseapeng on 2016/7/23.
 */
@WebServlet(name = "UpLoadPicServlet", urlPatterns = {"/student/UpLoadPicServlet"})
public class UpLoadPicServlet extends HttpServlet {
    private File uploadPath;
    private File tempPath;
    @Override
    public void init() throws ServletException {
        uploadPath = new File(getServletContext().getRealPath("upload"));
        System.out.println("uploadPath=====" + uploadPath);

        if (!uploadPath.exists()){
            uploadPath.mkdir();
        }

        tempPath = new File(getServletContext().getRealPath("temp"));
        if (!tempPath.exists()){
            tempPath.mkdir();
        }
        super.init();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("LoginUser");
        System.out.println("UpLoadPicServlet "+student.getT_username());
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(tempPath);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000*20);


        List fileltems = null;
        try {
            fileltems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String itemNo = "";
        for (Iterator iter = fileltems.iterator();iter.hasNext();) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                if ("itemNo".equals(item.getFieldName())) {
                    itemNo = item.getString();
                }
            }
            if (!item.isFormField()) {
                //上传文件的名称和完整路径
                String fileName = item.getName();

                long size = item.getSize();
                //判断是否选择了文件
                if ((fileName == null || fileName.equals("")) && size == 0) {
                    continue;
                }
                //截取字符串 如：C:\WINDOWS\Debug\PASSWD.LOG
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
                //System.out.println(fileName.substring(fileName.lastIndexOf(".")));

                // 保存文件在服务器的物理磁盘中：第一个参数是：完整路径（不包括文件名）第二个参数是：文件名称
                //item.write(file);
                //修改文件名和物料名一致，且强行修改了文件扩展名为gif
                String picName = student.getT_username()+fileName.substring(fileName.lastIndexOf("."));
                String picUrl = "..\\upload"+"\\"+ picName;
                try {
                    item.write(new File(uploadPath, picName));
                    student.setT_picture(picUrl);
                    student.setT_status(1);
                    SqlSession sqlSession = null;
                    sqlSession = MyBatisUtil.createSession();
                    if (sqlSession.update(Student.class.getName()+".updatepic",student)!=1){
                        System.out.println("保存失败");
                    }else {
                        sqlSession.commit();
                        MyBatisUtil.closeSqlSession(sqlSession);
                        System.out.println("success  "+student.getT_picture());
                        response.sendRedirect(request.getContextPath()+"/student/student.jsp");
                        return;
                    }
                } catch (Exception e) {
                    System.out.println("保存失败");
                    e.printStackTrace();
                }
                //将文件保存到目录下，不修改文件名
                //item.write(new File(uploadPath, fileName));
                //
                //
                ////将图片文件名写入打数据库
                //itemManager.uploadItemImage(itemNo, fileName);
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
